package com.shangxian.giveithome.service.impl;


import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.controller.ImgFeiServer;
import com.shangxian.giveithome.controller.MechanismServer;
import com.shangxian.giveithome.entity.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.AdoptionMapper;
import com.shangxian.giveithome.mapper.PetMapper;
import com.shangxian.giveithome.mapper.PlaceMapper;
import com.shangxian.giveithome.mapper.SearchMapper;
import com.shangxian.giveithome.service.PetFeiService;
import com.shangxian.giveithome.utils.MyBeanUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class PetFeiServiceImpl implements PetFeiService {

    @Resource
    private AdoptionMapper adoptionMapper;

    @Resource
    private PlaceMapper placeMapper;

    @Resource
    private SearchMapper searchMapper;

    @Resource
    private PetMapper petMapper;

    @Resource
    private MechanismServer mechanismServer;

    @Resource
    private ImgFeiServer imgFeiServer;

    /**
     * 根据用户id查询已领养信息
     *
     * @param id       用户id
     * @param pageable 分页数据
     */
    @Override
    public PageableDetails queryByUserAdop(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = adoptionMapper.countByUsAdoption(id);
        if (count == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        List<Adoption> adoptions = adoptionMapper.queryByUsAdopTion(id, pageNumber * pageSize, pageSize);
        //收集宠物id集合
        List<Long> petIds = adoptions.stream().map(Adoption::getPetId).collect(Collectors.toList());
        //收集图片id集合
        List<Long> imgIds = adoptions.stream().map(Adoption::getImgId).collect(Collectors.toList());
        List<PlaceDetails> placeDetailsList = stePlaceDetailsList(petIds);
        List<Img> imgs = steImgList(imgIds);
        List<AdoptionDetails> list = new ArrayList<>();
        //收集机构id集合
        List<Long> mes = adoptions.stream().map(Adoption::getMeId).collect(Collectors.toList());
        boolean mech = false;
        //若是在机构领养的则可以查询机构信息若不是则不需要添加机构信息
        List<Mechanism> mechanismList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mes)) {
            mechanismList = mechanismServer.queryByUserAdoption(mes);
            mech = true;
        }
        boolean finalMech = mech;
        Iterator<PlaceDetails> petIterator = placeDetailsList.iterator();
        Iterator<Mechanism> mechanismIterator = mechanismList.iterator();
        adoptions.forEach(adoption -> {
            PlaceDetails placeDetails  = new PlaceDetails();
            while (petIterator.hasNext()) {
                PlaceDetails itPet = petIterator.next();
                if (itPet.getId().equals(adoption.getPetId())) {
                    placeDetails = itPet;
                    petIterator.remove();
                    break;
                }
            }
            AdoptionDetails adopt = new AdoptionDetails(placeDetails);
            adopt.setCounty(placeDetails.getCounty());
            if (finalMech) {
                while (mechanismIterator.hasNext()) {
                    Mechanism mechanism = mechanismIterator.next();
                    if (mechanism.getId().equals(adoption.getMeId())) {
                        adopt.setMechanismName(mechanism.getName());
                        mechanismIterator.remove();
                        break;
                    }
                }
            }
            List<Img> im = new ArrayList<>();
            for (Img img : imgs) {
                if (img.getKeyId().equals(adoption.getImgId())) {
                    im.add(img);
                    break;
                }
            }
            adopt.setImg(im);
            list.add(adopt);
        });
        return returnPageable(pageNumber, pageSize, count, list);
    }

    /**
     * 查看已送养-待领养相关数据
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails queryByPlaceUs(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = placeMapper.countByUsAPlace(id);
        if (count == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        List<Place> places = placeMapper.queryByPlaceUs(id, pageNumber * pageSize, pageSize);
        List<PlaceDetails> list = setPlaceList(places);
        return returnPageable(pageNumber, pageSize, count, list);
    }


    /**
     * 查看已送养-历史相关数据
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails queryByPlaceHistory(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = placeMapper.countByUsAPlaceHistory(id);
        if (count == 0) {
            return null;
        }
        List<Place> places = placeMapper.queryByPlaceHistoryUs(id, pageNumber * pageSize, pageSize);
        List<PlaceDetails> list = setPlaceList(places);
        return returnPageable(pageNumber, pageSize, count, list);
    }

    /**
     * 查询寻主-寻找中
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails searchPeople(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = searchMapper.searchPeopleCount(id);
        if (count == 0) {
            return null;
        }
        List<SearchPeople> searchPeopleList = searchMapper.searchPeopleRelationship(id, pageNumber * pageSize, pageSize);
        List<SearchPeopleDetails> searchPeopleDetails = setSearchPeopleList(searchPeopleList);
        return returnPageable(pageNumber, pageSize, count, searchPeopleDetails);
    }

    /**
     * 查询寻主-已找到
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails searchPeopleHistory(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = searchMapper.searchPeopleCountHistory(id);
        if (count == 0) {
            return null;
        }
        List<SearchPeople> searchPeopleList = searchMapper.searchPeopleRelationshipHistory(id, pageNumber * pageSize, pageSize);
        List<SearchPeopleDetails> searchPeopleDetails = setSearchPeopleList(searchPeopleList);
        return returnPageable(pageNumber, pageSize, count, searchPeopleDetails);

    }

    /**
     * 查询寻宠-寻找中
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails searchPet(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = searchMapper.searchPetCount(id);
        if (count == 0) {
            return null;
        }
        List<SearchPet> searchPeopleList = searchMapper.searchPetRelationship(id, pageNumber * pageSize, pageSize);
        List<SearchPetDetails> searchPetDetails = setSearchPetList(searchPeopleList);
        return returnPageable(pageNumber, pageSize, count, searchPetDetails);
    }

    /**
     * 查询寻宠-已找到
     *
     * @param id       用户id
     * @param pageable 分页数据
     * @return
     */
    @Override
    public PageableDetails searchPetHistory(Long id, Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        //总条数
        Integer count = searchMapper.searchPetCountHistory(id);
        if (count == 0) {
            return null;
        }
        List<SearchPet> searchPeopleList = searchMapper.searchPetRelationshipHistory(id, pageNumber * pageSize, pageSize);
        List<SearchPetDetails> searchPeopleDetails = setSearchPetList(searchPeopleList);

        return returnPageable(pageNumber, pageSize, count, searchPeopleDetails);
    }

    /**
     * 返回
     *
     * @param pageNumber 当前页
     * @param pageSize   每页条数
     * @param count      总条数
     * @param list       返回数据
     * @param <T>        泛型
     * @return
     */
    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }

    /**
     * 送养查询数据处理
     *
     * @param places 数据
     * @return
     */
    public List<PlaceDetails> setPlaceList(List<Place> places) {

        List<PlaceDetails> list = new ArrayList<>();
        List<Long> petIds = places.stream().map(Place::getPetId).collect(Collectors.toList());
        List<Long> imgIds = places.stream().map(Place::getImgId).collect(Collectors.toList());
        List<Long> mes = places.stream().map(Relationship::getMeId).collect(Collectors.toList());
        List<Pet> pets = stePetList(petIds);
        List<Img> imgs = steImgList(imgIds);
        boolean mech = false;
        List<Mechanism> mechanismList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mes)) {
            mechanismList = mechanismServer.queryByUserAdoption(mes);
            mech = true;
        }
        boolean finalMech = mech;
        //Iterator<Pet> petIterator = pets.iterator();
        //Iterator<Mechanism> mechanismIterator = mechanismList.iterator();
        List<Mechanism> finalMechanismList = mechanismList;
        places.forEach(place -> {
            Pet pet = new Pet();
            for (Pet p : pets) {
                if (p.getId().equals(place.getPetId())) {
                    pet = p;
                    pets.remove(p);
                    break;
                }
            }
//            while (petIterator.hasNext()) {
//                Pet itPet = petIterator.next();
//                if (itPet.getId().equals(place.getPetId())) {
//                    pet = itPet;
//                    petIterator.remove();
//                    break;
//                }
//            }
            PlaceDetails placeDetails = new PlaceDetails(pet);
            if (finalMech) {
                for (Mechanism m : finalMechanismList) {
                    if (m.getId().equals(placeDetails.getMeId())) {
                        placeDetails.setMechanismName(m.getName());
                        finalMechanismList.remove(m);
                        break;
                    }
                }
//                while (mechanismIterator.hasNext()) {
//                    Mechanism next = mechanismIterator.next();
//                    if (next.getId().equals(placeDetails.getMeId())) {
//                        placeDetails.setMechanismName(next.getName());
//                        mechanismIterator.remove();
//                        break;
//                    }
//                }
            }
            MyBeanUtils.copyBeanNull(place, placeDetails);
            List<Img> im = new ArrayList<>();
            for (Img img : imgs) {
                if (img.getKeyId().equals(place.getImgId())) {
                    im.add(img);
                    break;
                }
            }
            placeDetails.setImg(im);
            list.add(placeDetails);
        });
        return list;
    }

    /**
     * 寻主查询数据处理
     *
     * @param searchPeopleList 数据
     * @return
     */
    private List<SearchPeopleDetails> setSearchPeopleList(List<SearchPeople> searchPeopleList) {
        List<SearchPeopleDetails> list = new ArrayList<>();
        List<Long> petIds = searchPeopleList.stream().map(SearchPeople::getPetId).collect(Collectors.toList());
        List<Long> imgIds = searchPeopleList.stream().map(SearchPeople::getImgId).collect(Collectors.toList());
        List<Pet> pets = stePetList(petIds);
        System.out.println(pets);
        List<Img> imgs = steImgList(imgIds);
        System.out.println(imgs);
//        Iterator<Pet> petIterator = pets.iterator();
        searchPeopleList.forEach(searchPeople -> {
//            Pet pet = new Pet();
//            while (petIterator.hasNext()) {
//                Pet itPet = petIterator.next();
//                if (itPet.getId().equals(searchPeople.getPetId())) {
//                    pet = itPet;
//                    petIterator.remove();
//                    break;
//                }
//            }
            SearchPeopleDetails searchPeopleDetails = null;
            for (Pet pet:pets) {
                if (searchPeople.getPetId().equals(pet.getId())){
                    searchPeopleDetails = new SearchPeopleDetails(pet);
                    break;
                }
            }
            MyBeanUtils.copyBeanNull(searchPeople, searchPeopleDetails);
            List<Img> im = new ArrayList<>();
            for (Img img : imgs) {
                if (img.getKeyId().equals(searchPeople.getImgId())) {
                    im.add(img);
                    break;
                }
            }
            searchPeopleDetails.setImg(im);
            list.add(searchPeopleDetails);
        });
        return list;
    }

    /**
     * 寻主查询数据处理
     *
     * @param searchPetList 数据
     * @return
     */
    private List<SearchPetDetails> setSearchPetList(List<SearchPet> searchPetList) {
        List<SearchPetDetails> list = new ArrayList<>();
        List<Long> petIds = searchPetList.stream().map(SearchPet::getPetId).collect(Collectors.toList());
        List<Long> imgIds = searchPetList.stream().map(SearchPet::getImgId).collect(Collectors.toList());
        List<Pet> pets = stePetList(petIds);
        List<Img> imgs = steImgList(imgIds);
        searchPetList.forEach(searchPet -> {
            AtomicReference<Pet> pet = new AtomicReference<>(new Pet());
            for (Pet petes : pets) {
                if (petes.getId().equals(searchPet.getPetId())) {
                    pet.set(petes);
                    break;
                }
            }
            SearchPetDetails searchPetDetails = new SearchPetDetails(pet.get());
            MyBeanUtils.copyBeanNull(searchPet, searchPetDetails);
            List<Img> im = new ArrayList<>();
            for (Img img : imgs) {
                if (img.getKeyId().equals(searchPet.getImgId())) {
                    im.add(img);
                    break;
                }
            }
            searchPetDetails.setImg(im);
            list.add(searchPetDetails);
        });
        return list;
    }

    private List<PlaceDetails> stePlaceDetailsList(List<Long> petIds) {
        List<PlaceDetails> pets = petMapper.queryByUsPlaceDetails(petIds);
        if (CollectionUtils.isEmpty(pets)) {
            return new ArrayList<>();
        }
        return pets;
    }

    private List<Pet> stePetList(List<Long> petIds) {
        List<Pet> pets = petMapper.queryByUsPet(petIds);
        if (CollectionUtils.isEmpty(pets)) {
            return new ArrayList<>();
        }

        return pets;
    }

    private List<Img> steImgList(List<Long> imgIds) {
        List<Img> imgs = imgFeiServer.queryImagesByIds(imgIds);
        if (CollectionUtils.isEmpty(imgs)) {
            return new ArrayList<>();
        }
        return imgs;
    }
}
